package com.tianji.aigc.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.tianji.aigc.agent.AbstractAgent;
import com.tianji.aigc.agent.Agent;
import com.tianji.aigc.entity.vo.ChatEventVO;
import com.tianji.aigc.enums.AgentTypeEnum;
import com.tianji.aigc.enums.ChatEventTypeEnum;
import com.tianji.aigc.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Map;
//@Service
//@RequiredArgsConstructor
public class AgentServiceImpl implements ChatService {

    @Override
    public Flux<ChatEventVO> chat(String question, String sessionId) {
        //先通过路由智能体分析用户意图返回对应编号即枚举名字，这里未用Stream流
        String result = findAgentByType(AgentTypeEnum.ROUTE).process(question, sessionId);
        AgentTypeEnum agentTypeEnum = AgentTypeEnum.agentNameOf(result);
        Agent agent = findAgentByType(agentTypeEnum);
        if(agent == null){
            //找不到智能体直接返回结果
            ChatEventVO chatEventVO = ChatEventVO.builder()
                    .eventType(ChatEventTypeEnum.DATA.getValue())
                    .eventData(result)
                    .build();
            return Flux.just(chatEventVO, AbstractAgent.STOP_EVENT);
        }
        //否则执行对应的智能体逻辑注意后续的智能体都是Stream流
        return agent.processStream(question, sessionId);
    }

    /**
     * 根据代理类型查找对应的Agent实例
     *
     * @param agentTypeEnum 要查找的代理类型
     * @return 与给定类型匹配的Agent实例，如果未找到或类型为null则返回null
     */
    private Agent findAgentByType(AgentTypeEnum agentTypeEnum) {
        if(agentTypeEnum == null){
            return null;
        }
        //从 Spring 容器中查找所有实现了 Agent 接口的实例。多态
        //Key 是 Bean 名称，Value 是对应的 Agent 实例。
        Map<String, Agent> beans = SpringUtil.getBeansOfType(Agent.class);
        //遍历所有的Agent的bean找到匹配的类型
        for (Agent agent : beans.values()) {
            if(agentTypeEnum == agent.getAgentType()){
                return agent;
            }
        }
        return null;

    }
    @Override
    public void stop(String sessionId) {
        findAgentByType(AgentTypeEnum.ROUTE).stop(sessionId);
    }

    @Override
    public String chatText(String question) {
        return "";
    }
}
